//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2004
//
// Dialog for editing rectangle coordinates.
//

# include "StdAfx.h"
# include "Resource.h"
# include "EditRect.h"
# include "PtAlgo.h"
# include "EditHelpers.h"
# include "PrintUnits.h"
# include "Globals.h"

static
INT_PTR CALLBACK EditProc (HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) {
	switch (_uMsg) {
		case WM_INITDIALOG: {
			rect_t * const pRect = reinterpret_cast<rect_t *> (_lParam);
			::SetWindowLong (_hWnd, GWL_USERDATA, _lParam);

			char buf [20];
			PrintLon (buf, pRect->x0);
			::SetDlgItemText (_hWnd, IDC_LEFT, buf);
			PrintLon (buf, pRect->x1);
			::SetDlgItemText (_hWnd, IDC_RIGHT, buf);
			PrintLat (buf, pRect->y0);
			::SetDlgItemText (_hWnd, IDC_BOTTOM, buf);
			PrintLat (buf, pRect->y1);
			::SetDlgItemText (_hWnd, IDC_TOP, buf);

			::EnableWindow (::GetDlgItem (_hWnd, IDOK), FALSE);

			return TRUE;
		}

		case WM_COMMAND: {
			switch (LOWORD (_wParam)) {
				case IDC_LEFT:
				case IDC_TOP:
				case IDC_RIGHT:
				case IDC_BOTTOM: {
					if (HIWORD (_wParam) == EN_CHANGE) {
						if (
							ValidateAsArc (::GetDlgItem (_hWnd, IDC_LEFT))  &&
							ValidateAsArc (::GetDlgItem (_hWnd, IDC_TOP))   &&
							ValidateAsArc (::GetDlgItem (_hWnd, IDC_RIGHT)) &&
							ValidateAsArc (::GetDlgItem (_hWnd, IDC_BOTTOM)) &&
							GetTextAsArc (::GetDlgItem (_hWnd, IDC_LEFT))   < GetTextAsArc (::GetDlgItem (_hWnd, IDC_RIGHT)) &&
							GetTextAsArc (::GetDlgItem (_hWnd, IDC_BOTTOM)) < GetTextAsArc (::GetDlgItem (_hWnd, IDC_TOP))
						) {
							::EnableWindow (::GetDlgItem (_hWnd, IDOK), TRUE);
						} else
							::EnableWindow (::GetDlgItem (_hWnd, IDOK), FALSE);
					}
					return TRUE;
				}

				case IDOK: {
					rect_t * const pRect = reinterpret_cast<rect_t *> (::GetWindowLong (_hWnd, GWL_USERDATA));

					pRect->x0 = GetTextAsArc (::GetDlgItem (_hWnd, IDC_LEFT));
					pRect->x1 = GetTextAsArc (::GetDlgItem (_hWnd, IDC_RIGHT));
					pRect->y0 = GetTextAsArc (::GetDlgItem (_hWnd, IDC_BOTTOM));
					pRect->y1 = GetTextAsArc (::GetDlgItem (_hWnd, IDC_TOP));

					::EndDialog (_hWnd, 0);

					return TRUE;
				}

				case IDCANCEL:
					::EndDialog (_hWnd, 1);
					return TRUE;
			}
		}
	}

	return FALSE;
}

bool EditRect (HWND _hWnd, rect_t & _rect) {
	return DlgBox (IDD_EDIT_RECT, _hWnd, EditProc, reinterpret_cast<LPARAM> (& _rect)) == 0;
}